#pragma once

#include <iostream>
#include <sys/select.h>
#include <sys/time.h>
#include "Socket.hpp"

using namespace std;
static const uint16_t defaultport = 8888; 
static const int fd_num_max = sizeof(fd_set) * 8;  
int defaultfd = -1;

class SelectServer
{
public:
    SelectServer(uint16_t port = defaultport):_port(port)
    {
        for(int i = 0; i < fd_num_max; i++)
        {
            fd_arry[i] = defaultfd;
        }
    }

    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        return true;
    }

    void PrintFd()
    {
        cout << "online fd list: ";
        for (int i = 0; i < fd_num_max; i++)
        {
            if(fd_arry[i] == defaultfd) continue;
            cout << fd_arry[i] <<" ";
        }
        cout << endl;
    }
    void Accepter()
    {
        //连接事件就绪，可以accept了
        string clientip;
        uint16_t clientport = 0;
        int sock = _listensock.Accept(clientip,clientport);
        if(sock < 0) return;
        lg(Info, "accept success, %s: %d, sock fd: %d", clientip.c_str(), clientport, sock);

        int i =1;
        for( ; i < fd_num_max; i++)
        {
            if(fd_arry[i] != defaultfd) continue;
            else break;
        }
        if(i == fd_num_max)//说明便利整个数组结束，发现没有位置了，直接关闭该套接字fd
        {
            lg(Warning, "server is full, close %d now!", sock);
            close(sock);
        }
        else
        {
            //不能立刻读，要把它写进数组，否则如果读没就绪，会一直阻塞
            fd_arry[i] = sock;
            PrintFd();
        }

    }

    void Recver(int fd, int pos)
    {
        //读就绪
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if(n < 0)
        {
            lg(Warning, "recv error: fd is : %d", fd);
            close(fd);
            fd_arry[pos] = defaultfd; // 这里本质是从select中移除
        }
        else if(n == 0)
        {
            lg(Info, "client quit, me too, close fd is : %d", fd);
            close(fd);
            fd_arry[pos] = defaultfd; //从select移除
        }
        else
        {
            buffer[n] = 0;
            cout << "get a messge: " << buffer << endl;
        }
    }

    void Dispatcher(fd_set& rfd)
    {
        //我们不知道哪个fd唤醒了，所以需要从fd_arry里遍历
        for(int i =0; i < fd_num_max; i++)
        {
            int fd = fd_arry[i];
            if(fd == defaultfd) continue;
            if(FD_ISSET(fd, &rfd))//fd在rfd，说明准备就绪了
            {
                //如果fd==套接字，说明要建立新连接，
                if(fd == _listensock.Sockfd())
                {
                    Accepter();//连接新管理
                }
                //fd != 套接字，说明读的就绪准备了
                else
                {
                    Recver(fd, i);
                }
            }
        }
    }

    void Start()
    {
        int listensock = _listensock.Sockfd();
        fd_arry[0] = listensock;//将第一个元素设为套接字fd
        while(true)
        {
            fd_set rfds;
            FD_ZERO(&rfds);//清空rfds
            int maxfd = fd_arry[0];
            for(int i = 0; i < fd_num_max; i++)
            {
                //判断fd_arry[i]是否为有效，如果无效跳过，有效则写进rfds
                if(fd_arry[i] == defaultfd) continue;
                FD_SET(fd_arry[i], &rfds);
                //设置最大maxfd
                if(maxfd < fd_arry[i])
                {
                    maxfd = fd_arry[i];
                    lg(Info, "max fd update, max fd is: %d", maxfd);
                }
            }

            //创建timeval，但是不用
            struct timeval timeout ={0, 0};

            //进行select多路复用
            int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr);
            switch (n)
            {
            case 0:
                cout << "time out, timeout: " << timeout.tv_sec << "." << timeout.tv_usec << endl;
                break;
            case -1:
                cerr << "select error" << endl;
            default://有时间就绪了， todo
                cout << "get a new link..." << endl;
                Dispatcher(rfds);
                break;
            }
        }
    }
    


    ~SelectServer(){}
private:
    Sock _listensock;
    uint16_t _port;
    int fd_arry[fd_num_max];
};